package com.example.administrator.xxnapp.fragment.mine;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.example.administrator.xxnapp.R;
import com.example.administrator.xxnapp.bean.UserBean;
import com.example.administrator.xxnapp.fragment.mine.about.AboutActivity;
import com.example.administrator.xxnapp.http.HttpUrl;
import com.example.administrator.xxnapp.login.IViewUser;
import com.example.administrator.xxnapp.login.LoginActivity;
import com.example.administrator.xxnapp.login.UserPresenter;
import com.example.administrator.xxnapp.main.MainActivity;
import com.example.administrator.xxnapp.ui.ItemTextRawLayout;
import com.example.administrator.xxnapp.user.UserInfoActivity;
import com.example.administrator.xxnapp.util.Config;
import com.example.administrator.xxnapp.util.GlideBlurformation;
import com.example.administrator.xxnapp.util.glide.CornersTransform;
import com.gyf.barlibrary.BarHide;
import com.gyf.barlibrary.ImmersionBar;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.mdruby.baselibrary.BaseFragment;
import cn.mdruby.baselibrary.utils.ABAppUtil;
import cn.mdruby.baselibrary.utils.ObjectStoreUtil;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import cn.smssdk.gui.RegisterPage;

/**
 */
public class MineFragment extends BaseFragment implements IViewMine,IViewUser{
    protected ImmersionBar mImmersionBar;
    private static MineFragment fragment;
    private MinePresenter mPresenter;
    @BindView(R.id.frag_mine_IV_top_Background)
    ImageView mIVBackground;
    @BindView(R.id.frag_mine_IV_HeadImage)
    ImageView mIVHeadImage;
    @BindView(R.id.user_info_head_layout_TV_Name)
    TextView mTVName;
    @BindView(R.id.user_info_head_layout_TV_Describe)
    TextView mTVDescribe;
    @BindView(R.id.user_info_head_layout_IV)
    ImageView mIVHead;
    private UserBean mUser;
    private String password;
    private UserPresenter mUserPresenter;

    public static MineFragment getInstance(){
        if (fragment == null){
            synchronized (MineFragment.class){
                if (fragment == null){
                    fragment = new MineFragment();
                }
            }
        }
        return fragment;
    }

    @Override
    public int getLayoutId() {
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar
                .fitsSystemWindows(false)
                .transparentStatusBar()
                .fixMarginAtBottom(true);
        return R.layout.fragment_mine;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && mImmersionBar != null){
            mImmersionBar = ImmersionBar.with(this);
            mImmersionBar
                    .fitsSystemWindows(false)
                    .transparentStatusBar()
                    .fixMarginAtBottom(true);
//            mImmersionBar.init();
        }
    }

    @Override
    public void initBeforeDatas() {
        mUser = (UserBean) ObjectStoreUtil.getObject(mContext, Config.Key.USER_OBJECT_KEY);
        mPresenter = new MinePresenter(this,new UserBean());
        mUserPresenter = new UserPresenter(this,new UserBean());
    }

    @Override
    public void initViews(View view) {
        ButterKnife.bind(this,view);
    }

    @Override
    public void setListeners() {
        RequestOptions options = new RequestOptions();
        options.centerCrop()
                .transform(new CircleCrop())
                .error(R.mipmap.ic_launcher)
                .fallback(R.mipmap.ic_launcher);
        Glide.with(mContext).load(mPresenter.getHeadImage()).apply(options).into(mIVHeadImage);

        RequestOptions options1 = new RequestOptions();
        options1.centerCrop()
                .optionalCenterCrop()
                .transform(new GlideBlurformation(getActivity()));
        Glide.with(getActivity()).load(mPresenter.getHeadImage()).apply(options1).into(mIVBackground);

        mIVHeadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });


//       sendCode(getActivity());

        setUserHeadInfo(mUser);
    }

    @OnClick(R.id.user_info_head_layout)
    public void userInfo(View view){
        Intent intent = new Intent(mContext, UserInfoActivity.class);
        startActivityForResult(intent,Config.RequestCode.USER_INFO);
    }

    private void setUserHeadInfo(UserBean bean) {
        mTVName.setText(bean.getUserName());
        mTVDescribe.setText(bean.getGender().equals(UserBean.Gender.female)?"女":"男");

//        Glide.with(this).load(bean.getHeadImage()).into(mIVHead);
        RequestOptions options = new RequestOptions();
        options.transform(new CornersTransform(mContext,10 ));
        options.error(R.mipmap.ic_launcher);
        Glide.with(this).load(HttpUrl.BASE_URL_BASE+mUser.getHeadImage()).apply(options).into(mIVHead);
    }

    public void sendCode(Context context) {
        RegisterPage page = new RegisterPage();
        page.setRegisterCallback(new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 处理成功的结果
                    HashMap<String,Object> phoneMap = (HashMap<String, Object>) data;
                    String country = (String) phoneMap.get("country"); // 国家代码，如“86”
                    String phone = (String) phoneMap.get("phone"); // 手机号码，如“13800138000”
                    // TODO 利用国家代码和手机号码进行后续的操作
                    Toast.makeText(mContext, "=="+country+"="+phone, Toast.LENGTH_SHORT).show();
                } else{
                    // TODO 处理错误的结果
                    Toast.makeText(mContext, "失败了="+event+"-"+result, Toast.LENGTH_SHORT).show();
                }
            }
        });
        page.show(context);
    }

    @Override
    public void loadUserData() {

    }

    @OnClick(R.id.frag_mine_TV_Exit)
    public void exit(View view){
        SharedPreferences preferences = getActivity().getSharedPreferences(Config.ShareKey.SHARED_PREFRENCES_NAME,Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = preferences.edit();
        edit.putBoolean(Config.ShareKey.REMEMBER_PASSWORD_KEY,false);
        edit.commit();
        Intent intent = new Intent(mContext, LoginActivity.class);
        startActivity(intent);
        getActivity().finish();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresenter.destroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.RequestCode.USER_INFO){
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Config.ShareKey.SHARED_PREFRENCES_NAME, Context.MODE_PRIVATE);
            String password = sharedPreferences.getString(Config.ShareKey.USER_PASSWORD, "");
            Log.e(TAG, "onActivityResult: "+password );
            mUserPresenter.signIn(mUser.getUserPhone(),password);
        }
        if (resultCode == getActivity().RESULT_OK){
            switch (requestCode){
            /*    case Config.RequestCode.USER_INFO:

                    break;*/
            }
        }
    }

    @OnClick(R.id.fragmine_ITRLayout_About)
    public void about(View view){
        Intent intent = new Intent(mContext, AboutActivity.class);
        startActivity(intent);
    }

    @Override
    public void loginSuccess(UserBean bean) {
        Log.e(TAG, "onActivityResult loginSuccess: "+bean.getHeadImage());
        ObjectStoreUtil.saveObject(mContext,Config.Key.USER_OBJECT_KEY,bean);
        mUser = (UserBean) ObjectStoreUtil.getObject(mContext,Config.Key.USER_OBJECT_KEY);
        setUserHeadInfo(mUser);
    }

    @Override
    public void loginError(String message) {
        Log.e(TAG, "onActivityResult loginError: "+message );
           mUser = (UserBean) ObjectStoreUtil.getObject(mContext,Config.Key.USER_OBJECT_KEY);
           setUserHeadInfo(mUser);
    }
}
